<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ContentWrap } from '@/components/ContentWrap'
import { getUserDetail, addUser, editUser } from '@/api/user/admin'
import { ElMessage, ElForm } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 表单数据
const form = reactive({
  userId: '',
  phone: '',
  password: '',
  name: '',
  branch: '',
  sex: 3
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
      validator: (rule: any, value: string, callback: any) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }
    },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  branch: [{ required: true, message: '请输入网点', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

const formRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(false)
const isEdit = ref(false)

// 性别选项
const sexOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 },
  { label: '未知', value: 3 }
]

// 获取用户详情
const fetchUserDetail = async (userId: string) => {
  try {
    loading.value = true
    const res = await getUserDetail(userId)
    if (res.code === 200) {
      const userData = res.data
      form.userId = userData.userId
      form.phone = userData.phone
      form.name = userData.name
      form.branch = userData.branch
      form.sex = userData.sex
      // 密码不返回，保留为空
    } else {
      ElMessage.error(res.message || '获取用户详情失败')
    }
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 准备提交的数据
        const formData = {
          ...form,
          sex: Number(form.sex)
        }

        let res
        if (isEdit.value) {
          // 编辑模式：如果密码为空，则不提交密码字段
          if (!formData.password) {
            delete formData.password
          }
          res = await editUser(formData)
          if (res.code === 200) {
            ElMessage.success('更新成功')
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增模式
          res = await addUser(formData)
          if (res.code === 200) {
            ElMessage.success('创建成功')
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }

        if (res.code === 200) {
          // 跳转到用户列表页面并携带刷新参数
          router.push({
            name: 'UserPageList',
            query: { refresh: '1' }
          })
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回用户列表
const goBack = () => {
  router.push({ name: 'UserPageList' })
}

onMounted(() => {
  const userId = route.params.id as string
  if (userId && userId !== '0') {
    isEdit.value = true
    fetchUserDetail(userId)
  } else {
    isEdit.value = false
  }
})
</script>

<template>
  <ContentWrap
    :title="isEdit ? '编辑顾客' : '新增顾客'"
    :message="isEdit ? '编辑顾客信息' : '添加新的顾客信息'"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 500px"
      :disabled="loading"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          :placeholder="isEdit ? '请输入新密码（不修改请留空）' : '请输入密码'"
          show-password
        />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="网点" prop="branch">
        <el-input v-model="form.branch" placeholder="请输入网点" />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option
            v-for="item in sexOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ isEdit ? '更新' : '提交' }}
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<style scoped>
:deep(.el-form-item__content) {
  justify-content: flex-start;
}
</style>
